package net.arogarth.aws.android.manager.views;

import java.util.ArrayList;
import java.util.List;

import net.arogarth.aws.android.lib.AmazonEc2;
import net.arogarth.aws.android.lib.AwsRequestException;
import net.arogarth.aws.android.lib.models.Ec2ElasticIp;
import net.arogarth.aws.android.lib.models.Ec2ElasticIp.Ec2Domain;
import net.arogarth.aws.android.lib.models.Ec2Instance;
import net.arogarth.aws.android.manager.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ElIpList extends Activity {
	public class ElIpListAdapter extends BaseAdapter implements AdapterView.OnItemLongClickListener {

		private final List<Ec2ElasticIp> elips = new ArrayList<Ec2ElasticIp>();
		
		private Context context;

		public ElIpListAdapter(Context view, ListView list) {
			this.context = view;

			list.setAdapter(this);
			list.setOnItemLongClickListener(this);
			this.loadData();
		}

		private void loadData() {
			final ProgressDialog pd = ProgressDialog.show(this.context,
					"Please Wait...", "Loading Data...", true, false);

			final Thread t = new Thread() {
				public void run() {
					AmazonEc2 aec2 = new AmazonEc2();

					try {
						List<Ec2ElasticIp> _elips= aec2.describeAddresses();

						elips.clear();
						for (Ec2ElasticIp elip : _elips) {
							elips.add(elip);
						}
						
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								notifyDataSetChanged();
								pd.dismiss();
							}
						});
					} catch (final AwsRequestException e) {
//						runOnUiThread(new Runnable() {
//							public void run() {
//								Toast.makeText(_context, e.getMessage(), Toast.LENGTH_SHORT).show();
//								finish();
//							}
//						});
					}
				}
			};
			t.start();
		}

		public int getCount() {
			return this.elips.size();
		}

		public Ec2ElasticIp getItem(int arg0) {
			return (Ec2ElasticIp) this.elips.get(arg0);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final Ec2ElasticIp elip = (Ec2ElasticIp) getItem(position);

			final LinearLayout _ll = (LinearLayout) LayoutInflater.from(
					this.context).inflate(R.layout.ec2_elip_list_item, parent,
					false);

			((TextView) _ll.findViewById(R.id.elasticIp)).setText(elip.getPublicIp());
			((TextView) _ll.findViewById(R.id.instanceId)).setText(elip.getInstanceId());
			
			return _ll;
		}

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, final View arg1,
				int arg2, long arg3) {
			
			final Ec2ElasticIp elip = this.getItem(arg2);
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
			builder.setTitle("Options");

			final ArrayList<String> options = new ArrayList<String>();
			final ArrayList<String> map = new ArrayList<String>();
			
			if( elip.getInstanceId() == "" ) {
				options.add("Release");
				map.add("release");
				options.add("Associate");
				map.add("associate");
			}
			else {
				options.add("View Instance");
				map.add("view_instance");
				options.add("Associate");
				map.add("associate");
				options.add("Disassociate");
				map.add("disassociate");
			}
			
			
			
			
			builder.setItems(options.toArray(new String[options.size()]), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, final int which) {
					String action = map.get(which);
					
					if ( action == "associate" ) {
						final ProgressDialog pd = ProgressDialog.show(context,
								"Please Wait...", "Loading Data...", true, false);

						final Thread t = new Thread() {
							public void run() {
								try {
									final List<Ec2Instance> instances = new AmazonEc2().descriptInstances();
									
									runOnUiThread(new Runnable() {
										public void run() {
											pd.dismiss();
											showAssociateInstancePopUp(elip, instances);
										}
									});
								} catch (Exception e) { e.printStackTrace(); }
							}
						};
						pd.show();
						t.run();
						
					} else if ( action == "disassociate" ) {
						
						DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
						        if (which == DialogInterface.BUTTON_NEGATIVE) return;
								
								final ProgressDialog _pd = ProgressDialog.show(context,
										"Please Wait...", "Disassociate Instance...", true, false);
								
								final Thread _t = new Thread() {
									public void run() {
										try {
											new AmazonEc2().disassociateAddress(elip.getPublicIp());
											
											runOnUiThread(new Runnable() {
												public void run() {
													_pd.dismiss();
													loadData();
												}
											});
										} catch (Exception e) { e.printStackTrace(); }
									}
								};
								_pd.show();
								_t.run();
							}
						};
						
						AlertDialog.Builder builder = new AlertDialog.Builder(context);
						builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
						    .setNegativeButton("No", dialogClickListener).show();
						
					} else if ( action == "release" ) {
						// TODO
						Toast.makeText(context, "NOT IMPLEMENTED YET", Toast.LENGTH_SHORT).show();
						
					} else if ( action == "view_instance" ) {
						Bundle b = new Bundle();
						
						String[] strArray = new String[1];
						strArray[0] = elip.getInstanceId();
						
						b.putStringArray("instances", strArray);
						Intent i = new Intent(arg1.getContext(), Ec2InstanceList.class);
						i.putExtras(b);
						
						startActivity(i);
					}
				}
			});
			
			builder.show();
			return false;
		}
		
		private void showAssociateInstancePopUp(final Ec2ElasticIp elip, final List<Ec2Instance> instances) {
			try {
				final String[] instanceIds = new String[instances.size()];
				int i=0;
				for(Ec2Instance instance : instances) instanceIds[i++] = instance.getInstanceId();
				
				AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
				builder.setTitle("Select Instances to Associate");
				
				builder.setItems(instanceIds,  new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, final int which) {
							final ProgressDialog pd = ProgressDialog.show(context,
									"Please Wait...", "Assocaiate Instance", true, false);

							final Thread t = new Thread() {
								public void run() {
									try {
										new AmazonEc2().associateAddress(elip.getPublicIp(), instanceIds[which]);
										
										runOnUiThread(new Runnable() {
											@Override
											public void run() {
												pd.dismiss();
												loadData();
											}
										});
									} catch (AwsRequestException e) { e.printStackTrace(); }
								}
							};
							
							pd.show();
							t.run();
					}});
				builder.show();
			} catch ( Exception e ) { e.printStackTrace(); }
		}
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.basic_list);
		final ListView lv = (ListView) findViewById(R.id.contentlist);
		new ElIpListAdapter(ElIpList.this, lv);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.elastic_ip, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.itmAdd:
			AlertDialog.Builder builder = new AlertDialog.Builder(ElIpList.this);
			builder.setTitle("Select Instances to Associate");
			
			final String[] opt = new String[] {"EC2", "VPC"};
			builder.setItems(opt,  new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, final int which) {
					final ProgressDialog pd = ProgressDialog.show(ElIpList.this,
							"Please Wait...", "Allocating IP ...", true, false);
					
					final Thread t = new Thread() {
						public void run() {
							Ec2Domain domain = Ec2Domain.EC2;
							if( opt[which].equalsIgnoreCase("vpc") )
								domain = Ec2Domain.VPC;
							
							try {
								new AmazonEc2().allocateAddress(domain);
							} catch (AwsRequestException e) {
								e.printStackTrace();
							}
							
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									pd.dismiss();
								}
							});
						}
					};
					
					pd.show();
					t.start();
				}
			});
			
			builder.show();
			
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
